package com.ffapp.demo.message;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ffapp.demo.R;
import com.ffapp.demo.basis.Constants;
import com.ffapp.demo.bean.BaseListBean;
import com.ffapp.demo.bean.BaseListBeanXF;
import com.ffapp.demo.bean.BasisBean;
import com.ffapp.demo.bean.HomeGrideListBean;
import com.ffapp.demo.bean.HomeGrideListData;
import com.ffapp.demo.bean.MessageListBean;
import com.ffapp.demo.bean.MessageListData;
import com.ffapp.demo.home.HomeBaseActivity;
import com.ffapp.demo.home.HomeTabActivity;
import com.ffapp.demo.notice.NoticeDetailActivity;
import com.ffapp.demo.other.WebViewX5Activity;
import com.ffapp.demo.util.MyUtils;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

/**
 * 消息列表
 */
public class MessageListActivity extends HomeBaseActivity {

    @BindView(R.id.recyclerview)
    XRecyclerView mRecyclerView;
    private MyAdapterList mAdapter;
    private MessageListBean mListBean;

    @BindView(R.id.edit_search)
    EditText edit_search;
    String searchkey = "";
    boolean isSearch = false;


    @Override
    public void initViews() {
        setContentView(R.layout.base_xrecycler_with_top_and_search);
        setTitle("消息列表");
//        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setVerticalScrollBarEnabled(true);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mListBean.refresh();
                getList();
                EventBus.getDefault().post(new HomeTabActivity.EventHomeTab(HomeTabActivity.EVENT_REFRESH_MESSAGE_COUNT));
            }

            @Override
            public void onLoadMore() {
                getList();
            }
        });
        mRecyclerView.setPullRefreshEnabled(true);
        mRecyclerView.setLoadingMoreEnabled(true);

        findViewById(R.id.view_search_zone).setVisibility(View.GONE);
        setTitleRightText("一键已读", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onAllReadClick();
            }
        });

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        mListBean = new MessageListBean();
        setListView();
        getList();
        edit_search.setHint("请输入关键字");
        edit_search.setOnKeyListener(new View.OnKeyListener() {
            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(MessageListActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    //进行搜索操作的方法，在该方法中可以加入mEditSearchUser的非空判断
                    if(event.getAction() == KeyEvent.ACTION_UP){
                        search();
                    }
                }
                return false;
            }
        });
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView view, int action,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_SEARCH) {
                    search();
                }
                return true;
            }
        });
    }

    @OnClick(R.id.img_search)
    void search() {
        searchkey = edit_search.getText().toString().trim();
        mListBean.refresh();
        getList();
    }

    @OnClick(R.id.img_cancel)
    void searchCancel() {
        edit_search.setText("");
    }

    @OnClick(R.id.text_cancel)
    void canel() {
        edit_search.setText("");
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void onListViewComplete() {
        mRecyclerView.refreshComplete();
        mRecyclerView.loadMoreComplete();
        mRecyclerView.setLoadingMoreEnabled(mListBean.hasNextPage());
//        mRecyclerView.setLoadingMoreEnabled(false);
        setEmptyView();
    }

    private void setEmptyView() {
        if (mListBean == null || mListBean.getList().size() == 0) {
            findViewById(R.id.refresh_view).setVisibility(View.VISIBLE);
            findViewById(R.id.refresh_view).setOnClickListener(
                    new View.OnClickListener() {
                        public void onClick(View v) {
                            mRecyclerView.refresh();
                        }
                    });
        } else {
            findViewById(R.id.refresh_view).setVisibility(View.INVISIBLE);
        }
    }


    private void getList() {

        MyParams params = new MyParams();
        showProgress();

        params.put(BaseListBeanXF.PAGE_NAME, mListBean.getNextPage());
        params.put(BaseListBeanXF.PAGE_SIZE_NAME, BaseListBean.PAGE_SIZE);
        if(!TextUtils.isEmpty(searchkey)){
            params.put("keyWord",searchkey);
        }

        params.put("sendWay","APP");
        MyHttpUtils.post(Constants.URL_MESSAGE_LIST, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        MessageListBean bean = (MessageListBean) result;
                        mListBean.addListBean(bean);
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                        onListViewComplete();
                    }
                },
                0, MessageListBean.class);

    }

    private void onAllReadClick() {

        MyParams params = new MyParams();
        showProgress();
//        params.put("sendWay","APP");
        MyHttpUtils.post(Constants.URL_MESSAGE_ALL_READ, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        showToast(((BasisBean)result).getStatusInfo());
                        if(mListBean != null){
                            mListBean.setAllRead();
                            if(mAdapter != null)
                            mAdapter.notifyDataSetChanged();
                        }
                        EventBus.getDefault().post(new HomeTabActivity.EventHomeTab(HomeTabActivity.EVENT_REFRESH_MESSAGE_COUNT));
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        dismissProgress();
                    }
                },
                0, BasisBean.class);

    }

    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {

        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.message_list_item, viewGroup, false);
            return new ViewHolder(view);
        }


        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            return mListBean == null ? 0 : mListBean.getList().size();
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_title)
            public TextView text_title;
            @BindView(R.id.text_time)
            public TextView text_time;
            @BindView(R.id.text_content)
            public TextView text_content;
            @BindView(R.id.img_red_point)
            public ImageView img_red_point;
            @BindView(R.id.img_icon)
            public ImageView img_icon;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                MessageListData data = mListBean.getList().get(position);
                if(data.isRead_BOOLEAN()){
                    text_title.setTextColor(mContext.getResources().getColor(R.color.base_text_grey));
                    text_content.setTextColor(mContext.getResources().getColor(R.color.base_text_grey_light));
                    img_red_point.setVisibility(View.GONE);
                }else {
                    text_title.setTextColor(mContext.getResources().getColor(R.color.base_text_black));
                    text_content.setTextColor(mContext.getResources().getColor(R.color.base_text_grey));
                    img_red_point.setVisibility(View.VISIBLE);
                }
                text_title.setText(data.getTitle());
                text_time.setText(data.getCreateTime());
                text_content.setText(data.getContent());
                img_icon.setImageResource(data.getImgRes());
                list_item.setTag(position);

            }
            @OnClick(R.id.list_item)
            void onItemClick(View view){
                    int position = (int) view.getTag();
                     MessageListData listData = mListBean.getList().get(position);
                mListBean.getList().get(position).setReadStatus_READ();
//                     listData.setReadStatus_READ();
//                     notifyItemChanged(position);
                     notifyDataSetChanged();
                postMessageRead(listData);
                if(!TextUtils.isEmpty(listData.getMsgCode()) && listData.getMsgCode().equals(MessageListData.MSG_TYPE_NOTICE)){
                    if(!TextUtils.isEmpty(listData.getDeviceType()) && listData.getDeviceType().equals("1")){
                        showToast("请前往内网查看详情");
                    }else {
                        if( new HomeGrideListBean().getObjFromCache() == null)return;
                        HomeGrideListBean mListBeanEnterAll = (HomeGrideListBean) new HomeGrideListBean().getObjFromCache();
                        if(mListBeanEnterAll == null)return;
                        HomeGrideListData data = mListBeanEnterAll.searchDataByName("通知公告");
                        if (data != null && !TextUtils.isEmpty(listData.getDataId())) {
//                            String urlDetal = data.getUrl().replace("/notice", "/noticeDetail?id=" + listData.getDataId());
//                            WebViewX5Activity.toWebView(mContext, urlDetal, data.getName());
                            NoticeDetailActivity.toDetail(mContext,listData.getDataId());
                        }
                    }
                }else if(listData.getMsgCode().startsWith("ZD_VISIT")){
                    String url = MyUtils.getIp()+"/zhapp/auditDetail?id="+listData.getDataId()+"&activeKey=9";
                    WebViewX5Activity.toWebView(mContext, url,"");
                }
            }
        }
    }

    public final static int WARNLISTRESULT = 44;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == WARNLISTRESULT){
            mListBean.refresh();
            getList();
        }
    }

    private void postMessageRead(MessageListData messageListData){
        MyParams params = new MyParams();
        params.put("id",messageListData.getId());
        params.put("deviceId",messageListData.getDataId());
        params.put("orgCode",messageListData.getMsgCode());
        MyHttpUtils.post(Constants.URL_MESSAGE_READ, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        EventBus.getDefault().post(new HomeTabActivity.EventHomeTab(HomeTabActivity.EVENT_REFRESH_MESSAGE_COUNT));
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
//                        super.onFailure(httpWhat, result);
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                    }
                },
                0, BasisBean.class);
    }
}
